const router = require('koa-router')()
var fs =require('fs')
var path=require('path')
const multiparty = require("multiparty");
const multer = require('koa-multer');//加载koa-multer模块
/**添加探测站 */
router.post('/uploadimages',async(ctx,next)=>{
  let errsign={status:500,exception:null};
    let datasign={status:200,recordset:null};
    function loadimg() {
        let send_json={};
        return  new Promise((resolve,reject)=>{
            let form = new multiparty.Form({uploadDir:'./admin/public/images' });
            form.parse(ctx.req,function(err,fields,files){
                if(err){
                    // throw err;
                    console.log(err);//Error: write after end
                    send_json={
                        exception:"解析失败",
                        err:false
                    };
                    resolve(send_json);
                    // return send_json;
                }else{
                     console.log(fields);//除文件外的其他附带信息
                    // console.log("files = ",files);//文件信息
                    if(files!==undefined&&files!=={}&&files.file!==undefined){
                        // console.log(files.file);
                        if(files.file.length>0){
                            let filename = files.file[0].path;
                            let filetype = files.file[0].headers['content-type'];
                            let realname = files.file[0].originalFilename;
                            console.log("filename = ",filename);
                            console.log("filetype = ",filetype);
                            console.log("realname = ",realname);
                            if(filetype.indexOf("image/")>=0){
                                send_json={
                                    recordset:"上传成功",
                                    err:true
                                };
                                resolve(send_json);
                            }else{
                                send_json={
                                    exception:"上传失败",
                                    err:false
                                };
                                fs.unlinkSync(filename);//删除非图片文件
                                resolve(send_json);
                            }
                        }
                    }else{
                        send_json={
                            exception:"未上传文件",
                            err:false
                        };
                        resolve(send_json);
                    }
                }
            });
        });
    }
    await loadimg().then(r=>{
        // console.log("r = ",r);
        if(r.err===false){
            errsign["exception"]=r.exception;
            ctx.body=errsign;
        }else{
            datasign["recordset"]=r.recordset;
            ctx.body=datasign;
        }
    });
});
router.post('/addfacility',async(ctx,next)=>{
  let errsign={status:500,exception:null};
    let datasign={status:200,recordset:null};
    function loadimg() {
        let send_json={};
        return  new Promise((resolve,reject)=>{
            let form = new multiparty.Form({uploadDir:'./admin/public/images' });
            form.parse(ctx.req,function(err,fields,files){
                if(err){
                    // throw err;
                    console.log(err);//Error: write after end
                    send_json={
                        exception:"解析失败",
                        err:false
                    };
                    resolve(send_json);
                    // return send_json;
                }else{
                  for(var k in fields){
                      fields[k]=fields[k][0];
                  }
                     console.log(JSON.stringify(fields));//除文件外的其他附带信息
                     var fpath=path.join(__dirname,'../public/js/'+fields['r11']+'.json');
                     fs.writeFile(fpath,JSON.stringify(fields),function(err){
                      if(err){
                          console.error(err);
                      }else{
                        console.log('----------新增成功-------------');
                      }
                      
                    });
                    /* fs.exists(fpath,function(exists){
                       if(exists){
                        fs.writeFile(fpath,JSON.stringify(fields),function(err){
                          if(err){
                              console.error(err);
                          }else{
                            console.log('----------新增成功-------------');
                          }
                          
                        });
                       }else{
                         fs.mkdir(fpath,function(err){
                           if(err){
                            console.log('----------创建失败-------------'+err);
                           }else{
                            fs.writeFile(fpath,JSON.stringify(fields),function(err){
                              if(err){
                                  console.error(err);
                              }else{
                                console.log('----------新增成功-------------');
                              }
                              
                            });
                           }
                         })
                       }
                     })*/
                     
                    // console.log("files = ",files);//文件信息
                    if(files!==undefined&&files!=={}&&files.file!==undefined){
                        // console.log(files.file);
                        if(files.file.length>0){
                            let filename = files.file[0].path;
                            let filetype = files.file[0].headers['content-type'];
                            let realname = files.file[0].originalFilename;
                            console.log("filename = ",filename);
                            console.log("filetype = ",filetype);
                            console.log("realname = ",realname);
                            if(filetype.indexOf("image/")>=0){
                                send_json={
                                    recordset:"上传成功",
                                    err:true
                                };
                                resolve(send_json);
                            }else{
                                send_json={
                                    exception:"上传失败",
                                    err:false
                                };
                                fs.unlinkSync(filename);//删除非图片文件
                                resolve(send_json);
                            }
                        }
                    }else{
                        send_json={
                            exception:"未上传文件",
                            err:false
                        };
                        resolve(send_json);
                    }
                }
            });
        });
    }
    await loadimg().then(r=>{
        // console.log("r = ",r);
        if(r.err===false){
            errsign["exception"]=r.exception;
            ctx.body=errsign;
        }else{
            datasign["recordset"]=r.recordset;
            ctx.body=datasign;
        }
    });
});
router.get('/addstation', async (ctx, next) => {
  var station= ctx.query.station
  var point=ctx.query.point
  var ponits=point.split(",")
  if(ponits[0]&&ponits[1]){
    ponits[0]=Number(ponits[0])
    ponits[1]=Number(ponits[1])
  }
  var status=ctx.query.status
  var office=ctx.query.office
  console.log(station,ponits,status,office);
  
  // await ctx.render('index', {
  //   title: 'Hello Koa 2!'
  // })
  writeJson({
    "name": station,//地点
    "coord": ponits,//坐标
    "value": status,//点的颜色
    "flag":'station',
    "num": '234'//自定义
},office)//执行一下;
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/detail/:id',async(ctx, next)=>{
   await ctx.render('detail', {
    title: ctx.params.id
  })
});

router.get('/json', async (ctx, next) => {
  ctx.body = fs.readFileSync(path.join(__dirname,"../views/nodeaddStation.html"),"utf-8")
})
router.get('/index', async (ctx, next) => {
  ctx.body = fs.readFileSync(path.join(__dirname,"../views/index.html"),"utf-8")
})

//文件上传
//配置
var storage = multer.diskStorage({
  // //文件保存路径
  // destination: function (req, file, cb) {
  //   cb(null, 'public/uploads/')
  // },
  // //修改文件名称
  // filename: function (req, file, cb) {
  //   var fileFormat = (file.originalname).split(".");
  //   cb(null,Date.now() + "." + fileFormat[fileFormat.length - 1]);
  // }
  destination:'public/uploads/',                     //注意这里有个，
	//修改文件名
	filename:function(req,file,cb){
	    var fileFormat = (file.originalname).split(".");
    	    cb(null,Date.now() + "." + fileFormat[fileFormat.length - 1]);
	}
})
//加载配置
var upload = multer({ storage: storage });
//路由
router.post('/upload', upload.array('file'), async (ctx, next) => {
  var station= ctx.req.body.station
  var point=ctx.req.body.point
  var ponits=point.split(",")
  if(ponits[0]&&ponits[1]){
    ponits[0]=Number(ponits[0])
    ponits[1]=Number(ponits[1])
  }
  var status=ctx.req.body.status
  var office=ctx.req.body.office
  console.log(station,ponits,status,office);
  var imagePath=[];
  if(ctx.req.files){
    for(var f=0;f<ctx.req.files.length;f++){
      imagePath=imagePath.concat(ctx.req.files[f].filename);
    }
  }
  
  ctx.body = {
    filename: imagePath.join(",")//返回文件名
  }
});


//写入json文件选项
function writeJson(params,office){
  //现将json文件读出来
  var fpath=path.join(__dirname,'../../js/markPoint.json');
     fs.readFile(fpath,function(err,data){
      if(err){
          return console.error(err);
      }
      var mapdata = data.toString();//将二进制的数据转换为字符串
      mapdata = JSON.parse(mapdata);//将字符串转换为json对象
      mapdata.markPointData[office]=mapdata.markPointData[office].concat(params)
      // person.data.push(params);//将传来的对象push进数组对象中
      // person.total = person.data.length;//定义一下总条数，为以后的分页打基础
    //   mapdata.markPointData.jinanju.push({
    //     "name": "香坊站",//地点
    //     "coord": [126.686831,45.727225],//坐标
    //     "value": '3',//点的颜色
    //     "flag":'station',
    //     "num": '234'//自定义
    // });
 
    for(var i=0;mapdata.markPointData.jinanju.length;i++){
     if( mapdata.markPointData.jinanju[i].name=="香坊站"){
      mapdata.markPointData.jinanju.splice(i,1)
      break
     }

    }
      console.log(mapdata);
      var str = JSON.stringify(mapdata);//因为nodejs的写入文件只认识字符串或者二进制数，所以把json对象转换成字符串重新写入json文件中
       fs.writeFile(fpath,str,function(err){
          if(err){
              console.error(err);
          }
          console.log('----------新增成功-------------');
      })
    });
}


module.exports = router
